//
//  LoginViewController.m
//  Jingjing
//
//  Created by user on 15/11/9.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetPswViewController.h"

@interface LoginViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)UITableView  *loginTab;
@property(nonatomic,strong)UIButton     *loginBtn;
@property(nonatomic,strong)UIButton     *registerBtn;

@property(nonatomic,strong)UILabel     *forgetLabel;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    [self createTheNavigationBar];
    [self createUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
}
#pragma mark -------------创建导航栏及相关控件
-(void)createTheNavigationBar
{
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"登录"];
    [self.view addSubview:topView];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    backBtn.hidden = self.backBtHide;
    [topView addSubview:backBtn];
    
    self.registerBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-54.0f, 20.0f, 44.0f, 44.0f)];
    [self.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    self.registerBtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    self.registerBtn.titleLabel.textColor = [UIColor hexStringToColor:@"#FFFFFF"];
    [self.registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.registerBtn addTarget:self action:@selector(buttonRegistTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.registerBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:self.registerBtn];
}

- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self dismissViewControllerAnimated:TRUE completion:^(void){}];
}
-(void)createUI
{
    
    [self.view addSubview:self.loginTab];
    [self.loginTab addSubview:self.forgetLabel];
    [self.loginTab addSubview:self.loginBtn];
}

//表
-(UITableView *)loginTab
{
    if (!_loginTab) {
        _loginTab = [[UITableView alloc] initWithFrame:CGRectMake(16.0f, 64.0f+16.0f, SCREEN_WIDTH-32.0f, SCREEN_HEIGHT-64.0f-16.0f) style:UITableViewStylePlain];
        _loginTab.delegate = self;
        _loginTab.dataSource = self;
        _loginTab.rowHeight = 60.0f;
        _loginTab.backgroundColor = kColorGrayBackground;
        _loginTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _loginTab;
}

//登录按钮
-(UIButton *)loginBtn
{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-32.0f)/2-(100.0f/2), NH(_forgetLabel)+16.0f, 100.0f, 44.0f)];
        [_loginBtn addTarget:self action:@selector(buttonLoginTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        _loginBtn.layer.cornerRadius = 5;
        _loginBtn.layer.masksToBounds = YES;
        _loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
        [_loginBtn setBackgroundColor:kColorOrangeNormal forState:UIControlStateNormal];
        [_loginBtn setBackgroundColor:kColorOrangePressed forState:UIControlStateHighlighted];
        [_loginBtn setBackgroundColor:kColorOrangeDisabled forState:UIControlStateDisabled];
        _loginBtn.enabled = NO;
    }
    return _loginBtn;
}



- (UILabel*)forgetLabel
{
    if (!_forgetLabel) {
        _forgetLabel = [[UILabel alloc] initWithFrame:CGRectMake(24.0f, 136.0f, 100.0f, 44.0f)];
        _forgetLabel.text = @"忘记密码?";
        _forgetLabel.font = [UIFont systemFontOfSize:14.0f];
        NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:@"忘记密码?"];
        NSRange contentRange = {0, [content length]};
        [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
        _forgetLabel.attributedText = content;
        _forgetLabel.textColor = [UIColor lightGrayColor];
        _forgetLabel.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonForgetTapped:)];
        [_forgetLabel addGestureRecognizer:gesture];

    }
    
    return _forgetLabel;
}

#pragma mark-tableViewDelegate&datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

static UITextField *__textField;//记录当前的textField
static UITextField *__textFieldPwd;//记录当前的textField
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIView * separtor = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 59.5f, SCREEN_WIDTH - 32.0f, 0.5)];
        separtor.backgroundColor =  [UIColor hexStringToColor:@"#bdbdbd"];
        separtor.tag = 111;
        [cell.contentView addSubview:separtor];//分割线
        

        
        UILabel *userlabel = [[UILabel alloc]initWithFrame:CGRectMake(24.0f, 5.0f, 80.0f, 45.0f)];
        userlabel.tag = 1000;
        userlabel.font = [UIFont systemFontOfSize:16.0f];
        userlabel.textColor = kColorTEXT;
        [cell.contentView addSubview:userlabel];
        
        UITextField *userTF = [[UITextField alloc] initWithFrame:CGRectMake(94.0f, 5.0f, SCREEN_WIDTH - 94.0f- 24.0f, 45.0f)];
        userTF.tag = 2000;
        userTF.delegate = self;
        userTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        [userTF addTarget:self action:@selector(textFieldTapped:) forControlEvents:UIControlEventEditingChanged];
        [userTF setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        userTF.font = [UIFont systemFontOfSize:16.0f];
        userTF.borderStyle = UITextBorderStyleNone;
        userTF.textColor = kColorTEXT;
        [cell.contentView addSubview:userTF];
        
        
    }
    
    UILabel *userLabel = (UILabel*)[cell.contentView viewWithTag:1000];
    UITextField *text = (UITextField *)[cell.contentView viewWithTag:2000];
    UIView *separtor = (UIView*)[cell.contentView viewWithTag:111];
    
    if (indexPath.row==1) {
        separtor.hidden = YES;
    }else{
        separtor.hidden = NO;
    }

    
    if (indexPath.row==0) {
        
        userLabel.text = @"用户名";
        text.placeholder = @"请输入手机号";
        text.keyboardType = UIKeyboardTypeNumberPad;
        __textField = text;
    }
    if (indexPath.row==1) {
        userLabel.text = @"密码";
        text.placeholder = @"请输入密码";
        __textFieldPwd = text;
        text.secureTextEntry = YES;
    }
    
    return cell;
}

#pragma mark-忘记按钮方法
-(void)buttonForgetTapped:(id)sender
{
    ForgetPswViewController *forgetPswVC = [[ForgetPswViewController alloc]init];
    [self presentViewController:forgetPswVC animated:TRUE completion:^(void){}];
}

#pragma mark-登录按钮方法
-(void)buttonLoginTapped:(id)sender
{
    [self.view endEditing:YES];
    
    BOOL isPhone = [AccountTools validatePhoneNumber:__textField.text];
    if (__textField.text.length==0) {
        ALERT_VIEW(@"手机号码不能为空");
    }
    else if (__textFieldPwd.text.length==0)
    {
        ALERT_VIEW(@"密码不能为空");
        
    }
    else if (isPhone == NO)
    {
        ALERT_VIEW(@"手机号不正确");
    }
    else {
        //        发请求
        NSString *PSWStr = [NSString stringWithFormat:@"%@%@",__textField.text,__textFieldPwd.text];
        NSString *threePSWStr = [AccountTools md5:[AccountTools md5:[AccountTools md5:PSWStr]]] ;
        
        
    
        [[AnimationIndicator sharedIndicator] startAnimationWithLoadText:@"加载中..."];
        [AppGlobalClass PostDataWithNSstring:LOGIN_URL withDictionary:@{@"userCd":__textField.text,@"password":threePSWStr} success:^(NSDictionary *dictionary) {
            
            
            if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
            {
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                // 存取用户信息
                NSDictionary *dict = [listArray firstObject];
               
                
                [AccountTools SaveUserAddress:[AccountTools isEmpty:[dict objectForKey:@"address"]]?@"":[dict objectForKey:@"address"] createTime:[AccountTools isEmpty:[dict objectForKey:@"createTime"]]?@"":[dict objectForKey:@"createTime"] email:[AccountTools isEmpty:[dict objectForKey:@"email"]]?@"":[dict objectForKey:@"email"]  mobile:[AccountTools isEmpty:[dict objectForKey:@"mobile"]]?@"":[dict objectForKey:@"mobile"] position:[AccountTools isEmpty:[dict objectForKey:@"position"]]?@"":[dict objectForKey:@"position"] resultCode:[AccountTools isEmpty:[dict objectForKey:@"resultCode"]]?@"":[dict objectForKey:@"resultCode"] sex:[AccountTools isEmpty:[dict objectForKey:@"sex"]]?@"":[dict objectForKey:@"sex"] token:[dict objectForKey:@"token"] updateTime:[dict objectForKey:@"updateTime"] userCd:[dict objectForKey:@"userCd"] userHeadPhoto:[dict objectForKey:@"userHeadPhoto"] userId:[dict objectForKey:@"userId"] userName:[dict objectForKey:@"userName"] userTokenId:[dict objectForKey:@"userTokenId"] userType:[dict objectForKey:@"userType"] zipCode:[AccountTools isEmpty:[dict objectForKey:@"zipCode"]]?@"":[dict objectForKey:@"zipCode"]];
                
                
                [self dismissViewControllerAnimated:YES completion:^(void){}];
                ALERT_VIEW(@"登录成功");
                
            }else
            {
                NSString * str = [dictionary objectForKey:@"message"];
                
                ALERT_VIEW(str);
                
            }
            [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
            
        } failure:^(NSError *error) {
            
            [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
        } networkerror:^(NSString *networkerror) {
            
            [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
        }];
        
    }
    
    
    
}

#pragma mark-注册按钮方法
- (void)buttonRegistTapped:(id)sender
{
    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    [self presentViewController:registerVC animated:TRUE completion:^(void){}];
}

- (void)textFieldTapped:(UITextField *)textField
{
    
    if ([AccountTools isEmpty:__textField.text]==NO&&[AccountTools isEmpty:__textFieldPwd.text]==NO) {
        if (__textFieldPwd.text.length>=8) {
            _loginBtn.enabled = YES;
            
        }else{
            
            _loginBtn.enabled = NO;
           
            
        }

    }else{
        _loginBtn.enabled = NO;
        
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //解除键盘出现通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidShowNotification object:nil];
    //解除键盘隐藏通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidHideNotification object:nil];
}

//键盘下降
- (void)keyboardHide:(NSNotification *)noti
{
    
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    _loginTab.contentOffset = CGPointMake(0, 0);
    
    [UIView commitAnimations];
}

//键盘升起
- (void)keyboardShow:(NSNotification *)noti
{
    NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [value CGRectValue];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    if (keyboardFrame.origin.y != SCREEN_HEIGHT) {
        CGFloat a = _loginBtn.frame.origin.y+_loginBtn.frame.size.height+_loginTab.frame.origin.y+80.0f;
        if (a < keyboardFrame.origin.y) {
            _loginTab.contentOffset = CGPointMake(0, 0);
        }else
        {
            _loginTab.contentOffset = CGPointMake(0, 80);
        }
        
    }
    
    [UIView commitAnimations];
    
}

@end
